// pages/dutyweekItemListdetail/dutyweekItemListdetail.js

const app = getApp()
const util = require('../../util/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: 1,
    noMore: true,
    checkItemList: [],
    files: [],
    dealFiles: [],
    currentCheckpointId: 0,
    categoryid: 1,
    deduction: 0,
    minusStatus: 'disable',
    video: "",
    videoSrc: ""
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("app", app)
    //获得启动值
    this.setData({
      currentCheckpointId: parseInt(options.currentCheckpointId),
      classname: options.classname,
      classnameId: parseInt(options.classnameId),
      categoryId: parseInt(options.categoryId),
      currentcategory: options.currentcategory,
      classisdone: options.classisdone,
      address: options.currentcheckAddress
    })
    dd.setStorageSync({
      key: "item-classname",
      data: {
        name: options.classname,
        id: options.classnameId,
        num: options.classNum,
        categoryId: options.categoryId
      }
    })
    dd.setStorageSync({
      key: "item-classdata",
      data: {
        categoryId: options.categoryId,
        category: options.currentcategory
      }
    })
    console.log(options)
    dd.httpRequest({
      url: app.baseUrl + '/DingDing/DutyWeek/getDutyWeekConditionByCategoryIdAndClassId',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        schoolId: parseInt(app.globalData.departmentId),
        // schoolId: 13,
        categoryId: parseInt(options.categoryId),
        classnameId: parseInt(options.classnameId),
        userId: parseInt(app.globalData.userId),
        // userId: 20871
      }),
      dataType: 'json',
      success: res => {
        let nowDate = new Date();
        dd.setStorageSync({
          key: ' OrigincheckItemList',
          data: res.data
        })
        let checkItemList = []
        let hide
        let contentLength
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].photo) {
            if (res.data[i].photo.split(",").length == 3) {
              hide = true
            }
            else
              hide = false
          }
          else {
            hide = false
          }
          if (res.data[i].content) {
            contentLength = res.data[i].content.length
          }
          else {
            contentLength = 0
          }
          if (res.data[i].deduction > 0) {
            this.setData({
              minusStatus: 'normal'
            })
          }
          checkItemList.push({
            id: res.data[i].id,
            status: res.data[i].status,
            content: res.data[i].content,
            realname: res.data[i].realname,
            item: res.data[i].item,
            itemId: res.data[i].itemId,
            hide: hide,
            contentLength: contentLength,
            imgHttpUrl: res.data[i].photo ? res.data[i].photo.split(",") : [],//保存新上传的http
            time: res.data[i].createTime,
            photo: '',
            video: res.data[i].video,
            videoSrc: app.imageUrl + res.data[i].video,
            dealFiles: res.data[i].photo ? res.data[i].photo.split(",") : [],
            deduction: res.data[i].deduction
          })

        }
        console.log("checkItemList", checkItemList)
        let buttonflag = 0
        if (this.data.classisdone != 2) {
          buttonflag = 1
        }
        else {
          buttonflag = 0
        }

        this.setData({
          showAll: 0,
          loading: 0,
          connectTime: util.formatTime(nowDate),
          checkItemList: checkItemList,
          buttonflag: buttonflag
        })
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！',
          type: 'fail'
        })
      },
      complete: () => {
        this.setData({
          loading: 0
        })
      }
    })

  },

  onShow: function () {
    this.setData({
      hide: 0,
      loading: 0
    })
    let checkItemList = this.data.checkItemList
    if (checkItemList.length != 0) {
      this.setData({
        checkItemList: checkItemList
      })
    }
  },
  //checkItemList数据装箱
  switchChange: function (e) {
    console.log("e", e)
    // let detailIndex=e.currentTarget.dataset.detailIndex;
    let detailIndex = parseInt(e.id.split('-')[0])//switch标识
    console.log(e)
    let checkItemList = this.data.checkItemList;
    if (e.value == false) {
      checkItemList[detailIndex].status = 0
      checkItemList[detailIndex].deduction = 0
      checkItemList[detailIndex].content = ""
      checkItemList[detailIndex].video = ""
      checkItemList[detailIndex].videoSrc = ""
      checkItemList[detailIndex].realname = app.globalData.realname
      if (checkItemList[detailIndex].imgHttpUrl == null || checkItemList[detailIndex].imgHttpUrl.length == 0 || checkItemList[detailIndex].imgHttpUrl == undefined) {
        checkItemList[detailIndex].dealFiles = []
        checkItemList[detailIndex].imgHttpUrl = []
        checkItemList[detailIndex].hide = false
      }
      else {
        checkItemList[detailIndex].imgHttpUrl == this.data.checkItemList[detailIndex].dealFiles
        checkItemList[detailIndex].dealFiles = this.data.checkItemList[detailIndex].imgHttpUrl
      }
      checkItemList[detailIndex].realname = app.globalData.realname
      checkItemList[detailIndex].hide = false
    } else {
      checkItemList[detailIndex].status = 1
      checkItemList[detailIndex].deduction = 0
      checkItemList[detailIndex].content = ""
      checkItemList[detailIndex].video = ""
      checkItemList[detailIndex].videoSrc = ""
      checkItemList[detailIndex].realname = app.globalData.realname
      if (checkItemList[detailIndex].imgHttpUrl == null || checkItemList[detailIndex].imgHttpUrl == undefined || checkItemList[detailIndex].imgHttpUrl.length == 0) {
        checkItemList[detailIndex].dealFiles = []
        checkItemList[detailIndex].imgHttpUrl = []
      }
      else {
        checkItemList[detailIndex].imgHttpUrl == this.data.checkItemList[detailIndex].dealFiles
        checkItemList[detailIndex].dealFiles = this.data.checkItemList[detailIndex].imgHttpUrl
      }
    }
    if (checkItemList[detailIndex].dealFiles.length == 3) {
      checkItemList[detailIndex].hide = true
    }
    else {
      checkItemList[detailIndex].hide = false
    }
    this.setData({
      checkItemList: checkItemList,
    })
  },

  //自定义相机组件
  // toCamera: function (e) {
  //   let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
  //   let checkItemList = this.data.checkItemList;
  //   dd.navigateTo({
  //     url: '../../subpages/pages/cameraIdentified/cameraIdentified?address=' + this.data.address +
  //       '&recordContent=' + checkItemList[detailIndex].content + '&checkItemList=' + JSON.stringify(checkItemList)
  //       + '&type=4' + '&detailIndex=' + detailIndex + '&dutyCategory=' + this.data.currentcategory
  //   })
  // },


  chooseImage: function (e) {
    var that = this;
    dd.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        dd.showLoading({
          content: "图片上传中",
        })
        console.log("size", res)
        let tempImg = res.filePaths
        // var tempFilesSize = res.tempFiles[0].size;  //获取图片的大小，单位B
        
        // if (tempFilesSize <= 4 * 1024 * 1024) {
          for (let i = 0; i < tempImg.length; i++) {
            dd.uploadFile({
              url: app.baseUrl + '/DingDingSystem/fileUpload',
              filePath: res.filePaths[i],
              fileName: 'file',
              fileType:'image',
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: res => {

                console.log(res)
                if (res.data == "fail") {
                  dd.showToast({
                  content: "图片上传失败",
                  type: "fail",
                  duration:1500
                })
                } else {
                  dd.showToast({
                  content: "上传成功" ,
                  type:"success",
                  duration:1500,
                })
                  // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                  let detailIndex = parseInt(e.currentTarget.id.split('-')[0])//switch标识
                  let checkItemList = that.data.checkItemList
                  // checkItemList[detailIndex].imgHttpUrl.push(app.imageUrl + res.data)
                  // checkItemList[detailIndex].dealFiles.push(app.imageUrl + res.data)
                  checkItemList[detailIndex].dealFiles.push(tempImg[i])
                  checkItemList[detailIndex].imgHttpUrl.push(res.data)
                  // checkItemList[detailIndex].imgHttpUrl.push(tempImg[i])
                  checkItemList[detailIndex].imageNum++

                  that.setData({
                    checkItemList: checkItemList
                  })
                  if (checkItemList[detailIndex].dealFiles.length == 3) {
                    checkItemList[detailIndex].hide = true
                    that.setData({
                      checkItemList: checkItemList
                    })
                  }
                }
                dd.hideLoading()
              },
              fail: res => {
                dd.hideLoading()
                dd.showToast({
                content: "图片上传失败",
                type: "fail",
                duration:1500
              })
              }
            })

          }
        // }
        // else {    //图片大于4M，弹出一个提示框
        //   dd.hideLoading()
        //   dd.showToast({
        //     content: '上传图片不能大于4M!',
        //     type: 'fail'     
        //   })
        // }

      }
    })
  },

  previewImageDeal: function (e) {
    console.log(e)
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])//switch标识
    let current = e.currentTarget.id.split('-')[1]
    let checkItemList = this.data.checkItemList[detailIndex]
    let urls = checkItemList.dealFiles;
    console.log("urls", urls)
    console.log("current", current)
    dd.previewImage({
      current: current, // 当前显示图片的http链接索引
      urls: urls // 需要预览的图片http链接列表
    })
  },
  deleteImage: function (e) {

    console.log(e)
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])//switch标识
    let imgIndex = parseInt(e.currentTarget.id.split('-')[1])
    let checkItemList = this.data.checkItemList[detailIndex]
    let target = this.data.checkItemList[detailIndex].imgHttpUrl[imgIndex]
    let dealFilesLength = this.data.checkItemList[detailIndex].dealFiles.length


    console.log(target.split("image/")[1])
    dd.showActionSheet({
      items: ['删除这张照片'],
      success: res => {
        console.log(res)
        if (res.index!=-1) {
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteFile',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              filename: target.split("image/")[1]
            }),
            dataType: 'text',
            success: res => {
              let detailIndex = parseInt(e.currentTarget.id.split('-')[0])//switch标识
              let checkItemList = this.data.checkItemList
              checkItemList[detailIndex].dealFiles.splice(imgIndex, 1)
              checkItemList[detailIndex].imgHttpUrl.splice(imgIndex, 1)
              checkItemList[detailIndex].imageNum++
              if (checkItemList[detailIndex].dealFiles.length < 3) {
                checkItemList[detailIndex].hide = false
              }
              else {
                checkItemList[detailIndex].hide = true
              }
              this.setData({
                checkItemList: checkItemList
              })
              dd.showToast({
                content: "删除成功"
              })
            }
          })
        }
      }
    })
  },
  //新增扣分加减器
  /*点击减号*/
  bindMinus: function (e) {
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
    let checkItemList = this.data.checkItemList
    var deduction = checkItemList[detailIndex].deduction;
    if (deduction > 0) {
      deduction--;
    }
    checkItemList[detailIndex].deduction = deduction;
    var minusStatus = deduction > 0 ? 'normal' : 'disable';
    this.setData({
      checkItemList: checkItemList,
      minusStatus: minusStatus
    })
  },
  /*点击加号*/
  bindPlus: function (e) {
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
    let checkItemList = this.data.checkItemList
    var deduction = checkItemList[detailIndex].deduction;
    deduction++;
    checkItemList[detailIndex].deduction = deduction;
    var minusStatus = deduction > 0 ? 'normal' : 'disable';
    this.setData({
      checkItemList: checkItemList,
      minusStatus: minusStatus
    })
  },
  /*输入框事件*/
  bindManual: function (e) {
    var deduction = app.trim(e.detail.value)
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
    let checkItemList = this.data.checkItemList
    var minusStatus = deduction > 0 ? 'normal' : 'disable';
    checkItemList[detailIndex].deduction = parseInt(deduction)
    this.setData({
      minusStatus: minusStatus,
      checkItemList: checkItemList
    })
  },


  inputContent: function (e) {
    e.detail.value = app.trim(e.detail.value)
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
    let checkItemList = this.data.checkItemList
    checkItemList[detailIndex].contentLength = parseInt(e.detail.value.length)
    checkItemList[detailIndex].content = e.detail.value
    this.setData({
      checkItemList: checkItemList
    })
  },

  submit: util.throttle(function (e) {

    let type = e.target.dataset.type;
    let checkItemList = this.data.checkItemList;
    let that = this;
    let commit
    let count = 0
    for (let i = 0; i < checkItemList.length; i++) {
      checkItemList[i].userId = app.globalData.userId;
      if (checkItemList[i].status == 0) {
        if (checkItemList[i].content == null || checkItemList[i].content == undefined || checkItemList[i].content == "") {
          commit = 0
        }
      } else if (checkItemList[i].status == 1) {
        count++
      }
    }
    if (commit == 0) {
      dd.showToast({
        content: '请输入现场问题描述',
      })
    } else if (count == checkItemList.length) {

      this.setData({
        isNormal: 0
      })
      // console.log("全部通过")
      dd.showActionSheet({
        items: [this.data.buttonflag ? "确定修改当前项目巡查结果，点击确定修改" : "确定提交当前项目巡查结果，点击确定提交"],
        success: res => {
          if (res.index != -1) {
            // console.log('用户点击确定')
            that.commitForm(type)
          }
        }
      })
    } else {
      // console.log("普通提交")
      that.commitForm(type)
    }
  }),

  commitForm: function (type) {
    console.log("type", type)
    let that = this;
    let noetime = new Date();
    dd.showLoading({
      content: '正在提交',
    })
    for (let i = 0; i < that.data.checkItemList.length; i++) {
      if (this.data.checkItemList[i].imgHttpUrl.length > 0){
        that.data.checkItemList[i].photo = that.data.checkItemList[i].imgHttpUrl.join(",")
      }else {
        that.data.checkItemList[i].photo = ""
      }
      let checkItemList = this.data.checkItemList
      if (checkItemList[i].video == null) {
        checkItemList[i].video = ""
      }
      if (checkItemList[i].deduction == null || checkItemList[i].deduction == undefined) {
        checkItemList[i].deduction = 0
        this.setData({
          checkItemList: checkItemList
        })
      }

    }
    if (type == "add") {
      console.log("categoryId", this.data.categoryId)
      console.log("checkItemList2", this.data.checkItemList)
      dd.httpRequest({
        url: app.baseUrl + '/DingDing/DutyWeek/addDutyWeekCondition',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify({
          schoolId: parseInt(app.globalData.departmentId),
          userId: parseInt(app.globalData.userId),
          realname: app.globalData.realname,
          classname: this.data.classname,
          classnameId: this.data.classnameId,
          categoryId: this.data.categoryId,
          createTime: util.formatTime(noetime),
          modifyTime: util.formatTime(noetime),
          category: this.data.currentcategory,
          data: this.data.checkItemList,
          checkpointId: parseInt(this.data.currentCheckpointId)
        }),
        dataType: 'text',
        success: res => {
          dd.showToast({
            content: '提交成功！',
            type: 'success'
          })
          setTimeout(function () {
            let pages = getCurrentPages(); //当前页面
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({ //直接给上移页面赋值
              submitRefresh: 1,

            });
            // 提示框隐藏后 跳转
            dd.navigateBack({
              delta: 1
            })
          }, 1000)

        },
        fail(res) {
          dd.showToast({
            content: '网络异常！',
            type: 'fail'
          })
        },
      })
    }
    else {
      dd.httpRequest({
        url: app.baseUrl + '/DingDing/DutyWeek/updateDutyWeekCondition',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify({
          schoolId: app.globalData.departmentId,
          userId: app.globalData.userId,
          realname: app.globalData.realname,
          classname: dd.getStorageSync({ key: 'item-classname' }).data.name,
          classnameId: dd.getStorageSync({ key: 'item-classname' }).data.id,
          categoryId: dd.getStorageSync({ key: 'item-classdata' }).data.categoryId,
          createTime: util.formatTime(noetime),
          modifyTime: util.formatTime(noetime),
          category: dd.getStorageSync({ key: 'item-classdata' }).data.category,
          data: that.data.checkItemList,
          isNormal: that.data.status,
          checkpointId: parseInt(this.data.currentCheckpointId)

        }),
        dataType: 'text',
        fail(res) {
          dd.showToast({
            content: '网络异常！',
            type: 'fail'
          })
        },
        success: res => {

          dd.showToast({
            content: '提交成功！',
            type: 'success'
          })
          setTimeout(function () {
            let pages = getCurrentPages(); //当前页面
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({ //直接给上移页面赋值
              submitRefresh: 1,

            });
            // 提示框隐藏后 跳转
            dd.navigateBack({
              delta: 1,

            })
          }, 1000)
          // }
        }
      })
    }
  },
  //新增视频录制功能
  press: function (e) {
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
    let checkItemList = this.data.checkItemList
    dd.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      success: res => {
        if (res.size > 2097152) {
          dd.showToast({
            content: '文件大于2M！',
            type: 'fail'
          })
        } else {
          let tempFilePath = res.tempFilePath
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload2',
            filePath: tempFilePath,
            fileName: 'file',
            fileType: 'video',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              console.log(res.data)
              checkItemList[detailIndex].video = res.data
              checkItemList[detailIndex].videoSrc = tempFilePath
              this.setData({
                checkItemList: checkItemList
              })
            }
          })
        }
      },
      fail(res) {
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo: function (e) {
    let detailIndex = parseInt(e.currentTarget.id.split('-')[0])
    let checkItemList = this.data.checkItemList
    let target = checkItemList[detailIndex].video
    dd.showActionSheet({
      items: ['删除视频'],
      success: res => {
        if (!res.cancel) {
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteVideo',
            method: 'POST',
            headers:{
              "Content-Type" : "application/json"
            },
            data: JSON.stringify({
              filename: target.split("video/")[1]
            }),
            dataType: 'text',
            success: res => {
              if (res.data == "success") {
                checkItemList[detailIndex].video = ""
                checkItemList[detailIndex].videoSrc = ""
                this.setData({
                  checkItemList: checkItemList
                })
              }
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})